<template>
	<view class="um-image">
		<image v-show="visible" :src="src" :style="styles" :mode="mode" @load="handleLoad" @error="handleError" />
		<view class="default" :style="styles" v-show="!visible">
			<um-icon name="pic-fill" class="icon" :size="20"></um-icon>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue';

const props = withDefaults(
	defineProps<{
		src?: string;
		width?: string;
		height?: string;
		mode?: string;
	}>(),
	{
		mode: 'widthFix',
		width: '100%'
	}
);

const visible = ref(false);

const handleError = (e: any) => {
	if (e.detail.errMsg) {
		visible.value = false;
	}
};

const handleLoad = (e: any) => {
	visible.value = true;
};

const styles = computed(() => {
	return {
		...(props.width ? { width: props.width } : {}),
		...(props.height ? { height: props.height } : {}),
		...(!visible.value && props.height === undefined ? { paddingTop: '100%' } : {})
	};
});
</script>

<style lang="scss" scoped>
.um-image {
	display: flex;
	overflow: hidden;
}

.default {
	position: relative;
	background-color: #e5e5e5;
	height: 100%;
}

.icon {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
}
</style>
